<?php
/*
 * coding: utf-8
 * +-------------------------------------------------------------------
 * | KL库 - MYSQL，MYSQLI，SQLITE模块
 * +-------------------------------------------------------------------
 * | Copyright (c) 2022-2099 KL库(https://www.fangheyun.xyz) All rights reserved.
 * +-------------------------------------------------------------------
 * | Author: 远易 <3431628590@qq.com>
 * +-------------------------------------------------------------------
 */

if(DB_TYPE == 'MYSQL'){
	exit("ERROR: MySQL extension has been abolished, please use advanced mysqli extension");
}else if(DB_TYPE == 'MYSQLI'){
    class DB {
        var $link = null;
        function __construct($db_host,$db_user,$db_pass,$db_name,$db_port){
            $this->link = mysqli_connect($db_host, $db_user, $db_pass, $db_name, $db_port);
            if ($this->link){
                mysqli_query($this->link,"set sql_mode = ''");
                mysqli_query($this->link,"set character set 'utf8'");
                mysqli_query($this->link,"set names 'utf8'");
                return true;
            }else{
                exit('ERROR: '.mysqli_connect_error());
            }
        }
		/**
		 * 获取数据表的数据，只可以用表值来获取信息
		 * @result 附属方法
		 */
		public function fetch($result=''){
			if($result == ''){
				exit('ERROR: Subsidiary method cannot be empty');
			}
			return mysqli_fetch_assoc($result);
		}
		/**
		 * 获取数据表的数据，可以用0123...或表值来获取信息
		 * @result 附属方法
		 */
		public function fetchs($result=''){
			if($result == ''){
				exit('ERROR: Subsidiary method cannot be empty');
			}
			return mysqli_fetch_array($result);
		}
		/**
		 * 获取数据表的数据
		 * @table 将要查询数据表数量的表名
		 * @array 条件数组
		 * 注: @array 若非数组则返回整张数据表的数据
		 */
		public function get_row($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value' AND ".$list;
				}
				$list = substr($list,0,-4);
				$sql = "SELECT * FROM `$table` WHERE $list";
			}else{
				$sql = "SELECT * FROM `$table`";
			}
			$result = mysqli_query($this->link,$sql);
			return mysqli_fetch_assoc($result);
		}
		/**
		 * 获取数据表中的数量
		 * @table 将要查询数据表数量的表名
		 * @array 条件数组
		 * 注: @array 若非数组则返回整张数据表的数量
		 */
		public function num_row($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value' AND ".$list;
				}
				$list = substr($list,0,-4);
				$sql = "SELECT * FROM `$table` WHERE $list";
			}else{
				$sql = "SELECT * FROM `$table`";
			}
			$result = mysqli_query($this->link,$sql);
			return mysqli_num_rows($result);
		}
		/**
		 * 获取数据表中的某一条
		 * @table 将要查询数据表数量的表名
		 * @num 某一条  注: 默认为0，相当于第一条
		 * @array 条件数组
		 * 注: @array 若非数组则返回整张数据表的数据
		 */
		public function count($table='',$num=0,$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value' AND ".$list;
				}
				$list = substr($list,0,-4);
				$sql = "SELECT * FROM `$table` WHERE $list";
			}else{
				$sql = "SELECT * FROM `$table`";
			}
			$result = mysqli_query($this->link,$sql);
			return mysqli_fetch_array($result)[$num];
		}
		/**
		 * SQl语句执行
		 * @sql 将要执行的SQL语句
		 */
		public function query($sql=''){
			if($sql == ''){
				exit('ERROR: SQL statement cannot be empty');
			}
			return mysqli_query($this->link,$sql);
		}
		/**
		 * fetch、fetchs 的附属方法
		 * @table 将要查询数据表数量的表名
		 * @array 条件数组
		 * 注: @array 若非数组则返回整张数据表的数据
		 */
		public function query_se($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value' AND ".$list;
				}
				$list = substr($list,0,-4);
				$sql = "SELECT * FROM `$table` WHERE $list";
			}else{
				$sql = "SELECT * FROM `$table`";
			}
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 字符串转义
		 * 1. 防止SQL Injection攻击，也就是你必须验证用户的输入
		 * 2. 操作数据的时候避免不必要的字符导致错误
		 * @str 字符串
		 */
		public function escape($str=''){
			if($str == ''){
				exit('ERROR: String cannot be empty');
			}
			return mysqli_real_escape_string($this->link,$str);
		}
		/**
		 * 插入数据表并获取插入后的ID
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
		 */
		public function insert($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(!is_array($array)){
				exit('ERROR: Incorrect data format');
			}
			$sql = "INSERT INTO `$table`";
			$sql .=" (`".implode("`,`",array_keys($array))."`) ";
			$sql .=" VALUES ('".implode("','",array_values($array))."') ";
			if(mysqli_query($this->link,$sql))
				return mysqli_insert_id($this->link); 
			return false;
		}
		/**
		 * 常用于执行SQL语句后，返回受影响的行数
		 */
		public function affected(){
			return mysqli_affected_rows($this->link);
		}
		/**
		 * 获取整张表的数据
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量可自定义，value值需对应数据表中的值
		 * @judge (True，False) 注: 默认为False，为True时（key变量）与（value值）相同不可改变，False反之
		 */
		public function json_array($table='',$array='',$judge=False){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			$sql = mysqli_query($this->link,"SELECT * FROM $table");
			if(is_array($array)){
				while($arr = mysqli_fetch_assoc($sql)){
					foreach($array as $key=>$value)
					{
						if($judge){
							$arrays[$value] = $arr[$value];
						}else{
							$arrays[$key] = $arr[$value];
						}
					}
					$list = json_encode($arrays, JSON_UNESCAPED_UNICODE).','.$list;
				}
			}else{
				while($arr = mysqli_fetch_assoc($sql)){
					$list = json_encode($arr, JSON_UNESCAPED_UNICODE).','.$list;
				}
			}
			return json_decode('['.substr($list,0,-1).']',true);
		}
		/**
		 * 搜索数据
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
		 * @arrays 数组(key变量=>value值) 注: key变量可自定义，value值需对应数据表中的值
		 * @judge (True，False) 注: 默认为False，为True时（key变量）与（value值）相同不可改变，False反之
		 */
		public function search_array($table='',$array='',$arrays='',$judge=False){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$lists = "$key LIKE '%$value%' AND ".$lists;
				}
				$sql = mysqli_query($this->link,"SELECT * FROM $table WHERE ".substr($lists,0,-4));
			}else{
				$sql = mysqli_query($this->link,"SELECT * FROM $table");
			}
			if(is_array($arrays)){
				while($arr = mysqli_fetch_assoc($sql)){
					foreach($arrays as $keys=>$values)
					{
						if($judge){
							$arrayss[$values] = $arr[$values];
						}else{
							$arrayss[$keys] = $arr[$values];
						}
					}
					$list = json_encode($arrayss, JSON_UNESCAPED_UNICODE).','.$list;
				}
			}else{
				while($arr = mysqli_fetch_assoc($sql)){
					$list = json_encode($arr, JSON_UNESCAPED_UNICODE).','.$list;
				}
			}
			return json_decode('['.substr($list,0,-1).']',true);
		}
		/**
		 * 插入数据
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
		 */
		public function insert_array($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(!is_array($array)){
				exit('ERROR: Incorrect data format');
			}
			$sql = "INSERT INTO `$table`";
			$sql .=" (`".implode("`,`",array_keys($array))."`) ";
			$sql .=" VALUES ('".implode("','",array_values($array))."') ";
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 编辑数据
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
		 * @arrays 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
		 */
		public function modify_array($table='',$array='',$arrays=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(!is_array($array)){
				exit('ERROR: Incorrect data format');
			}
			foreach($array as $key=>$value)
			{
				$list = "`$key`='$value', ".$list;
			}
			$list = substr($list,0,-2);
			if(is_array($arrays)){
				foreach($arrays as $keys=>$values)
				{
					$lists = "`$keys`='$values' AND ".$lists;
				}
				$lists = substr($lists,0,-4);
				$sql = "UPDATE `$table` SET $list WHERE $lists";
			}else{
				$sql = "UPDATE `$table` SET $list";
			}
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 删除数据
		 * @table 数据表名
		 * @array 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
		 */
		public function delete_array($table='',$array=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			if(is_array($array)){
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value' AND ".$list;
				}
				$list = substr($list,0,-4);
				$sql = "DELETE FROM `$table` WHERE $list";
			}else{
				exit('ERROR: To delete all data in the data table, use the "empty" function');
			}
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 清空数据表
		 * @table 数据表名
		 */
		public function empty_table($table=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			$sql = "TRUNCATE $table";
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 删除数据表  注: 谨慎使用！！！
		 * @table 数据表名
		 */
		public function delete_table($table=''){
			if($table == ''){
				exit('ERROR: Data table name cannot be empty');
			}
			$sql = "DROP TABLE $table";
			return mysqli_query($this->link,$sql);
		}
		/**
		 * 获取报错信息，常用于执行SQL语句之后返回报错信息
		 */
		public function error(){
			$error = mysqli_error($this->link);
			$errno = mysqli_errno($this->link);
			return 'ERROR: ('.$errno.')'.$error;
		}
		/**
		 * 关闭数据库连接
		 */
		public function close(){
			$sql = mysqli_close($this->link);
			return $sql;
		}
	}
}else if(DB_TYPE == 'SQLITE'){
	exit("ERROR: Temporarily discard SQLite");
}else{
    exit("ERROR: The database type can only be MySQL, mysqli, SQLite");
}
?>